// select 只负责等，一次可以等待多个fd
//  参数     fd_set 位图
/* 1、最多可以获得的fd + 1
    2、readfds      读集

    3、writefds     写集

    4  exceptfds    异常集
    5、struct timeval* 设置等待方式
*/
// 返回值
/*0 超时
    >0 有n个fd就绪
    <0 出错
*/
//缺点
/*
    等待的fd是有限的
    输入输出参数较多，数据拷贝的频率太高
    输入输出参数多，导致每次都要对fd进行事件重置
    使用第三方数组管理用户fd，用户层需要很多次遍历
        内核中检测fd事件就绪，也需要遍历
*/
#pragma once

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include "sockfd.hpp"

using namespace std;
static const uint16_t defaultport = 8080;
static const int fd_num_max = (sizeof(fd_set) * 8);
int defaultfd = -1;

class SelectServer
{
private:
    Sock _listen;
    uint16_t _port;
    //
    int fd_array[fd_num_max]; // 辅助数组
public:
    SelectServer(uint16_t port = defaultport) : _port(port)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            fd_array[i] = defaultfd;
            // cout<< "fd_array["<<i<<"]:"<<fd_array[i]<<endl;
        }
    }
    bool Init()
    {
        _listen.Socket();
        _listen.Bind(_port);
        _listen.Listen();

        return true;
    }
    void Accept()
    {
        string clientip;
        uint16_t clientport;
        int sock = _listen.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        lg(Info, "accept success,%s:%d,sock_fd:%d", clientip, clientport, sock);

        // 处理
        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            if (fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            lg(Warning, "server is full,close %d", sock);
            close(sock);
        }
        else
        {
            // 将链接添加到辅助数组
            fd_array[pos] = sock;
        }
    }
    void Recver(int fd,int pos)
    {
        char *buffer;
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if (n == 0)
        {
            lg(Info, "client quit,close fd:%d", fd);
            close(fd);
            fd_array[pos] = defaultfd;
        }
        else
        {
            lg(Warning, "read error fd:%d", fd);
            close(fd);
            fd_array[pos] = defaultfd;
        }
    }
    void Dispatcher(fd_set &rfds)//派发
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if (fd == defaultfd)
                continue;

            if (FD_ISSET(_listen.Fd(), &rfds))
            {
                if (fd == _listen.Fd()) // 或取新链接
                {
                    Accept();
                }
                else
                {
                    //
                    Recver(fd,i);
                }
            }
        }
    }
    void Start()
    {
        int listensock = _listen.Fd();

        struct timeval timeout = {5, 0};

        fd_array[0] = listensock;
        for (;;)
        {
            int maxfd = fd_array[0];
            fd_set rfds;
            FD_ZERO(&rfds); // 清空
            for (int i = 0; i < fd_num_max; i++)
            {
                if (fd_array[i] == defaultfd)
                    continue;
                FD_SET(fd_array[i], &rfds); // 添加到集合
                if (maxfd < fd_array[i])
                {
                    maxfd = fd_array[i];
                    lg(Info, "max fd update,max fd : %d", maxfd);
                }
            }

            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                cout << "time out timeout:" << timeout.tv_sec << ":" << timeout.tv_usec << endl;
                break;
            case -1:
                cerr << "select error" << endl;
                break;
            default:
                cout << "get a new link" << endl;
                Dispatcher(rfds);
                break;
            }
        }
    }
    ~SelectServer()
    {
        _listen.Close();
    }
};